﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Data;
using System.Data.Entity;
using IM.Manage.IDAL;
using IM.Manage.Models;

namespace IM.Manage.DAL.EF
{
    public class BaseDAL<TEntity> : IBaseDAL<TEntity> where TEntity : BaseModel
    {
        protected IMManageContext db = new IMManageContext();

        public virtual int GetMaxId()
        {
            return db.Set<TEntity>().Max().ID;
        }
        public virtual bool Exists(int id)
        {
            return db.Set<TEntity>().Where(t => t.ID == id).Count() > 0;
        }
        public virtual bool ExistsByCondition(Expression<Func<TEntity, bool>> expression)
        {
            return db.Set<TEntity>().Where(expression).Count() > 0;
        }

        public virtual int GetRecordCount()
        {
            return db.Set<TEntity>().Count();
        }
        public virtual int GetRecordCount(Expression<Func<TEntity, bool>> expression)
        {
            return db.Set<TEntity>().Where(expression).Count();
        }
        public virtual IList<TEntity> GetList()
        {
            return db.Set<TEntity>().ToList();
        }
        public virtual IList<TEntity> GetList(Expression<Func<TEntity, bool>> expression)
        {
            return db.Set<TEntity>().Where(expression).ToList();
        }
        public virtual TEntity GetEntity(int id)
        {
            return db.Set<TEntity>().Find(id);
        }

        public virtual int Create(TEntity t)
        {
            db.Set<TEntity>().Add(t);
            return db.SaveChanges();
        }
        public virtual int Update(TEntity t)
        {
            db.Entry<TEntity>(t).State = EntityState.Modified;
            return db.SaveChanges();
        }
        public virtual int Delete(int id)
        {
            TEntity t = db.Set<TEntity>().Find(id);
            db.Set<TEntity>().Remove(t);
            return db.SaveChanges();
        }

        public virtual int UpdateByCondition()
        {
            return 0;
        }
        public virtual int DeleteByCondition()
        {
            return 0;
        }
    }
}
